/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package CustomerGUIs;

import Model.Customer;
import Model.InternalDBManager;
import Supermarket.AppMessages;
import javax.persistence.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
 *
 * @author Manolis
 */
public class ListOfCustomerForm extends javax.swing.JFrame {
    
    private static EntityManager em;
    private int selectedRow=0;
    private Customer customer;
    private JFrame currentFrame;

    /**
     * Creates new form ListOfCustomerForm
     */
    public ListOfCustomerForm() {
        em = InternalDBManager.getEm();
        currentFrame = this;
        this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage());
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        customerQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT c FROM Customer c");
        customerList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(customerQuery.getResultList());
        CancelButton = new javax.swing.JButton();
        EditCustomerButton = new javax.swing.JButton();
        DeleteCustomerButton = new javax.swing.JButton();
        NewCustomerButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        CustomerListTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Επεξεργασία Στοιχείων Πελατών");

        CancelButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancel_16.png"))); // NOI18N
        CancelButton.setLabel("Ακύρωση");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        EditCustomerButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        EditCustomerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Edit_16.png"))); // NOI18N
        EditCustomerButton.setText("Τροποποίηση");
        EditCustomerButton.setEnabled(false);
        EditCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditCustomerButtonActionPerformed(evt);
            }
        });

        DeleteCustomerButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        DeleteCustomerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/remove_16.png"))); // NOI18N
        DeleteCustomerButton.setText("Διαγραφή");
        DeleteCustomerButton.setEnabled(false);
        DeleteCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteCustomerButtonActionPerformed(evt);
            }
        });

        NewCustomerButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        NewCustomerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/add_16.png"))); // NOI18N
        NewCustomerButton.setText("Δημιουργία");
        NewCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewCustomerButtonActionPerformed(evt);
            }
        });

        CustomerListTable.setColumnSelectionAllowed(true);
        CustomerListTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, customerList, CustomerListTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${customerId}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastName}"));
        columnBinding.setColumnName("Επίθετο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Διεύθυνση");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pointsCardNumber}"));
        columnBinding.setColumnName("Κάρτα Πόντων");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${availablePoints}"));
        columnBinding.setColumnName("Πόντοι");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${password}"));
        columnBinding.setColumnName("Password");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        CustomerListTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CustomerListTableMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(CustomerListTable);
        CustomerListTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        if (CustomerListTable.getColumnModel().getColumnCount() > 0) {
            CustomerListTable.getColumnModel().getColumn(0).setResizable(false);
            CustomerListTable.getColumnModel().getColumn(1).setResizable(false);
            CustomerListTable.getColumnModel().getColumn(2).setResizable(false);
            CustomerListTable.getColumnModel().getColumn(3).setResizable(false);
            CustomerListTable.getColumnModel().getColumn(4).setResizable(false);
            CustomerListTable.getColumnModel().getColumn(5).setResizable(false);
            CustomerListTable.getColumnModel().getColumn(6).setResizable(false);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(NewCustomerButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DeleteCustomerButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditCustomerButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 362, Short.MAX_VALUE)
                        .addComponent(CancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NewCustomerButton)
                    .addComponent(CancelButton)
                    .addComponent(DeleteCustomerButton)
                    .addComponent(EditCustomerButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    
    //Ελέγχει εάν ;egine επιλογή γραμμής από τη λίστα
    private void checkIfRowIsChosen() {
        //Εάν επιλεχθεί γραμμή-εγγραφή από τo πίνακα των πελατών 
        selectedRow = CustomerListTable.getSelectedRow();
        //Ενεργοποιεί buttons Εισαγωγή Πιστωτικής. Διαγραφή, Τροποποίηση
        //αν επιλεγεί Πελάτης (γραμμή του πίνακα) 
        DeleteCustomerButton.setEnabled(selectedRow >= 0);
        EditCustomerButton.setEnabled(selectedRow >= 0);
    }
    
    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void EditCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditCustomerButtonActionPerformed
        //Διαβάζουμε την επιλογή του χρήστη από τον πίνακα πελατών
        selectedRow = CustomerListTable.getSelectedRow();

        //Εάν η επιλογή είναι έγκυρη
        if (selectedRow >= 0) {
            //Διαβάζουμε τον επιλεγμένο πελάτη
            customer = customerList.get(selectedRow);
            EditCustomerForm editCustomerForm = new EditCustomerForm(currentFrame, true, customer);
            //Ο έλεγχος μεταφέρεται στην οθόνη καταχώρησης των στοιχείων πελάτη
            editCustomerForm.setVisible(true);
            //Εάν η διαδικασία τροποποίησης έχει ολοκληρωθεί
            if(editCustomerForm.getStatusUpdate()){
                //Ενημέρωση λίστας με την τροποποιημένη εγγραφή πελάτη
                customerList.set(selectedRow,customer);
            }
            editCustomerForm.dispose();
        }
        checkIfRowIsChosen();
    }//GEN-LAST:event_EditCustomerButtonActionPerformed

    private void DeleteCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteCustomerButtonActionPerformed
        //Διαβάζουμε την επιλογή του χρήστη από τον πίνακα πελατών
        selectedRow = CustomerListTable.getSelectedRow();

        //Εάν η επιλογή είναι έγκυρη
        if (selectedRow >= 0) {
            //Διαβάζουμε τον επιλεγμένο πελάτη
            customer = customerList.get(CustomerListTable.convertRowIndexToModel(selectedRow));
            //Εάν δεν συμμετέχει σε άλλα tables της ΒΔ (ως ξένο κλειδί)
            if ((customer.getPurchaseList().isEmpty()) && (customer.getChecksList().isEmpty())){
                //ζητείται επιβεβαίωση της διαγραφής
                int confirmChoice = AppMessages.DeleteDataConfirmationMessage(this);
                //Εάν επιβεβαιωθεί η διαγραφή
                if (confirmChoice==0){
                    try {
                        if (!em.getTransaction().isActive()){
                            em.getTransaction().begin();
                        }
                        //η εγγραφή του πελάτη αφαιρείται από τον entity manager
                        em.remove(customer);
                        //η εγγραφή διαγράφεται από τη λίστα και τη ΒΔ
                        customerList.remove (customer);
                        em.getTransaction().commit();
                        //και εμφανίζεται μήνυμα επιτυχίας
                        AppMessages.SuccessMessage(this);
                    } catch (SecurityException e) {
                        //διαφορετικά εμφανίζεται μήνυμα αδυναμίας διαγραφής
                        JOptionPane.showMessageDialog(this , e
                            ,"ΠΡΟΣΟΧΗ", JOptionPane.WARNING_MESSAGE);
                        em.getTransaction().rollback();
                    }
                }
            } else{
                //μήνυμα αδυναμίας διαγραφής (ξένο κλειδί)
                AppMessages.CannotDeleteMessage(this);
            }
        }
        this.setAlwaysOnTop(true);
        checkIfRowIsChosen();
    }//GEN-LAST:event_DeleteCustomerButtonActionPerformed

    private void NewCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewCustomerButtonActionPerformed

        //Δημιουργία φόρμας για εισαγωγή στοιχείων νέου πελάτη
        NewCustomerForm newCustomerForm = new NewCustomerForm(currentFrame, true);
        //Ο έλεγχος μεταφέρεται στην οθόνη καταχώρησης των στοιχείων πελάτη
        newCustomerForm.setVisible(true);
        //η φορμα είναι ζωντανή σε hide και έτσι μπορούμε
        //να πάρουμε τα δεδομένα της
        if (newCustomerForm.getStatusUpdate()){
        customerList.add(newCustomerForm.getData());
        }
        newCustomerForm.dispose();
    }//GEN-LAST:event_NewCustomerButtonActionPerformed

    private void CustomerListTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CustomerListTableMouseClicked
        //Ελέγχει άν έγινε επιλογή πελάτη από τον πίνακα
        checkIfRowIsChosen();
        //Διπλό κλικ κάνει τροποποίηση στοιχείων
        if (EditCustomerButton.isEnabled() && (evt.getClickCount() > 1)) {
            EditCustomerButtonActionPerformed(null);
        }
    }//GEN-LAST:event_CustomerListTableMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListOfCustomerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListOfCustomerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListOfCustomerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListOfCustomerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListOfCustomerForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JTable CustomerListTable;
    private javax.swing.JButton DeleteCustomerButton;
    private javax.swing.JButton EditCustomerButton;
    private javax.swing.JButton NewCustomerButton;
    private java.util.List<Model.Customer> customerList;
    private javax.persistence.Query customerQuery;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
